//
//  YZDKnowledgeViewController.m
//  YZOuterDiscxg
//
//  Created by apple on 17/8/10.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "YZDKnowledgeViewController.h"
#import "YZDKnowledgeCell.h"
#import <YYText.h>

static NSString * const identifier = @"YZDKnowledgeCell";

@interface YZDKnowledgeViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UIView *viewHeader;

@property (weak, nonatomic) IBOutlet UITableView *_tableView;

@property (weak, nonatomic) IBOutlet UILabel *labelTitle;

@property (nonatomic, copy) NSString *contentString;

@property (nonatomic, copy) NSString *subtitleString;

@property (nonatomic, assign) BOOL isExistId;//是否存在Id

@property (nonatomic, strong) NSString *timeString;

@property (nonatomic, strong) NSMutableAttributedString *totalAttributeString;

@end

@implementation YZDKnowledgeViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configView];
    [self configBackButton];
}

- (void)configView{
    [self._tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YZDKnowledgeCell class]) bundle:nil] forCellReuseIdentifier:identifier];
    self._tableView.backgroundColor = [YZMAppStyle colorForMain];
    [YZMAppStyle addLineViewWithParentView:self.viewHeader color:[YZMAppStyle colorForLineOfCell]];
//    self._tableView.estimatedRowHeight = 100;
    self._tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    self._tableView.showsVerticalScrollIndicator = NO;
    self.labelTitle.font = [YZMAppStyle largeSizeBoldFont];
    self.labelTitle.textColor = [YZMAppStyle colorForWhite];
    if (self.subtitleString.length > 0) {
        NSString *strTitle = self.subtitleString;
        NSMutableAttributedString *attributeTitle = [[NSMutableAttributedString alloc] initWithString:strTitle];
        if (self.timeString.length > 0) {
            strTitle = [strTitle stringByAppendingFormat:@"\n%@",self.timeString];
            attributeTitle = [[NSMutableAttributedString alloc] initWithString:strTitle];
            NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
            para.paragraphSpacingBefore = 10.f;
            para.alignment = NSTextAlignmentCenter;
            [attributeTitle addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0],NSParagraphStyleAttributeName:para} range:NSMakeRange(self.subtitleString.length, strTitle.length - self.subtitleString.length)];
        }
        self.labelTitle.attributedText = attributeTitle;
        self.viewHeader.backgroundColor = [YZMAppStyle colorForMain];
        self._tableView.tableHeaderView = self.viewHeader;
    }
}

- (void)configBackButton{
    NSArray *viewControllerArray = [self.navigationController viewControllers];
    long previousViewControllerIndex = [viewControllerArray indexOfObject:self] - 1;
    UIViewController *previous;
    if (previousViewControllerIndex >= 0) {
        previous = [viewControllerArray objectAtIndex:previousViewControllerIndex];
        previous.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
                                                     initWithTitle:@""
                                                     style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:nil];
        }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZDKnowledgeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (self.isExistId) {
        [cell configCellWithAttibuteString:self.totalAttributeString];
    }else{
        [cell configCellWithString:self.contentString];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isExistId) {
        return [YZDKnowledgeCell cellHeightForAttibuteString:self.totalAttributeString];
    }
    return [YZDKnowledgeCell cellHeightForString:self.contentString];
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZDKnowledgeViewController *knowledgeVc = [[YZDKnowledgeViewController alloc] init];
    [knowledgeVc updateParams:params];
    return knowledgeVc;
}

- (void)updateParams:(NSDictionary *)params{
    if (params == nil || params.allKeys.count == 0) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"baseterm" ofType:@"json"];
        NSData *data = [[NSData alloc] initWithContentsOfFile:path];
        params = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    }else{
        self.hidesBottomBarWhenPushed = YES;
    }
    self.title = params[@"title"];
    if ([params.allKeys containsObject:@"subtitle"]) {
        self.subtitleString = params[@"subtitle"];
    }
    if ([params.allKeys containsObject:@"time"]) {
        self.timeString = params[@"time"];
    }
    self.contentString = params[@"content"];
    NSArray *arrString = [self.contentString componentsSeparatedByString:@"#"];
    if (arrString.count > 1) {
        self.isExistId = YES;
        NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@""];
        for (NSInteger i = 0; i < arrString.count; i++) {
            NSMutableAttributedString * attributeStr = [self attributeStrTransFromString:arrString[i]];
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%ld.png",[params objectForKey:@"tag"],i+1]];
            [attributeString appendAttributedString:attributeStr];
            if (i < arrString.count - 1) {
                //                NSAttributedString *attribute = [NSAttributedString attributedStringWithAttachment:attach];
                //                [attributeString appendAttributedString:attribute];
                NSMutableAttributedString *attribute = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeScaleToFill attachmentSize:CGSizeMake([UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width * image.size.height / image.size.width) alignToFont:[YZMAppStyle mediumSizeFont] alignment:YYTextVerticalAlignmentCenter];
                [attributeString appendAttributedString:attribute];
                
            }
            
        }
        self.totalAttributeString = attributeString;
    }else{
        self.isExistId = YES;
        self.contentString = [self.contentString stringByReplacingOccurrencesOfString:@"\n" withString:@"\nPara"];
        NSArray *arrString = [self.contentString componentsSeparatedByString:@"Para"];
        NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@""];
        for (NSInteger i = 0; i < arrString.count; i++) {
            NSMutableAttributedString * attributeStr = [self attributeStrTransFromString:arrString[i]];
            [attributeString appendAttributedString:attributeStr];
        }
        self.totalAttributeString = attributeString;
    }
}


- (NSMutableAttributedString *)attributeStrTransFromString:(NSString *)string{
    NSString *str = string;
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:str];
    [attributeStr setYy_font:[YZMAppStyle mediumSizeFont]];
    [attributeStr setYy_color:[YZMAppStyle colorForWhite]];
    if ([str containsString:@"!"]) {
        str = [str stringByReplacingOccurrencesOfString:@"!" withString:@""];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineSpacing = 5.0f;
        paragraph.firstLineHeadIndent = 30.0f;
        NSDictionary *attributeDic = @{NSParagraphStyleAttributeName:paragraph};
        attributeStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributeDic];
        [attributeStr setYy_font:[YZMAppStyle mediumSizeFont]];
        [attributeStr setYy_color:[YZMAppStyle colorForWhite]];
        
    }else if([str containsString:@"paragraphSpacingAll"]){
        str = [str stringByReplacingOccurrencesOfString:@"paragraphSpacingAll" withString:@""];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineSpacing = 5.0f;
        paragraph.paragraphSpacingBefore = 10.0f;
        paragraph.paragraphSpacing  = 7.0f;
        NSDictionary *attributeDic = @{NSParagraphStyleAttributeName:paragraph};
        attributeStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributeDic];
        [attributeStr setYy_font:[YZMAppStyle mediumSizeFont]];
        [attributeStr setYy_color:[YZMAppStyle colorForWhite]];
    }else if ([str containsString:@"paragraphSpacingBefore"]){
        str = [str stringByReplacingOccurrencesOfString:@"paragraphSpacingBefore" withString:@""];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineSpacing = 5.0f;
        paragraph.paragraphSpacingBefore = 7.0f;
        NSDictionary *attributeDic = @{NSParagraphStyleAttributeName:paragraph};
        attributeStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributeDic];
        [attributeStr setYy_font:[YZMAppStyle mediumSizeFont]];
        [attributeStr setYy_color:[YZMAppStyle colorForWhite]];
    }else if ([str containsString:@"paragraphSpacing"]){
        str = [str stringByReplacingOccurrencesOfString:@"paragraphSpacing" withString:@""];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineSpacing = 5.0f;
        paragraph.paragraphSpacing  = 10.0f;
        NSDictionary *attributeDic = @{NSParagraphStyleAttributeName:paragraph};
        attributeStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributeDic];
        [attributeStr setYy_font:[YZMAppStyle mediumSizeFont]];
        [attributeStr setYy_color:[YZMAppStyle colorForWhite]];
    }else if ([str containsString:@"boldTitle"]){
        str = [str stringByReplacingOccurrencesOfString:@"boldTitle" withString:@""];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineSpacing = 5.0f;
        paragraph.paragraphSpacingBefore = 10.0f;
        paragraph.paragraphSpacing  = 7.0f;
        NSDictionary *attributeDic = @{NSFontAttributeName:[YZMAppStyle mediumSizeBoldFont],NSParagraphStyleAttributeName:paragraph};
        attributeStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributeDic];
        [attributeStr setYy_font:[YZMAppStyle mediumSizeBoldFont]];
        [attributeStr setYy_color:[YZMAppStyle colorForWhite]];
    }else if([str containsString:@"lineSpace"]){
        str = [str stringByReplacingOccurrencesOfString:@"lineSpace" withString:@""];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineSpacing = 5.0f;
        NSDictionary *attributeDic = @{NSParagraphStyleAttributeName:paragraph};
        attributeStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributeDic];
        [attributeStr setYy_font:[YZMAppStyle mediumSizeFont]];
        [attributeStr setYy_color:[YZMAppStyle colorForWhite]];
    }
    return attributeStr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
